package org.wxl.filter;

import io.jsonwebtoken.JwtException;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.wxl.utils.JWTUtils;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author 王学良
 */
@Component
@AllArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JWTUtils jwtUtils;
    private final UserDetailsService userDetailsService; // 注入用户服务

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain)
            throws IOException, ServletException {
        try {
            String token = resolveToken(request);

            if (token != null) {
                // 1. 解析Token中的用户名
                String username = jwtUtils.extractUsername(token);

                // 2. 加载用户信息
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                // 3. 完整验证（有效期+用户匹配）
                if (jwtUtils.validateToken(token, userDetails)) {
                    // 4. 构建认证对象
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(
                                    userDetails,
                                    null,
                                    userDetails.getAuthorities()
                            );

                    // 5. 存储到安全上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        } catch (JwtException | UsernameNotFoundException ex) {
            // Token验证失败或用户不存在
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的认证凭证");
            return;
        }

        chain.doFilter(request, response);
    }

    // 从请求头提取Token
    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
